<script setup lang="ts" name="ResetPassword">
import type { FormRules } from 'element-plus'
import { ProfileApi } from '@/api/system/user/profile'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const formData = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单校验
const equalToPassword = (_rule, value, callback) => {
  if (formData.value.newPassword !== value) {
    callback(new Error(t('profile.password', 'diffPwd')))
  } else {
    callback()
  }
}

// 表单校验
const formRules = reactive<FormRules>({
  oldPassword: [
    { required: true, message: t('profile.password', 'oldPwdMsg'), trigger: 'blur' },
    { min: 6, max: 20, message: t('profile.password', 'rule'), trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: t('profile.password', 'newPwdMsg'), trigger: 'blur' },
    { min: 6, max: 20, message: t('profile.password', 'rule'), trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: t('profile.password', 'cfPwdMsg'), trigger: 'blur' },
    { required: true, validator: equalToPassword, trigger: 'blur' }
  ]
})

const formRef = ref() // 表单 Ref
const submit = async () => {
  if (!formRef.value) return
  const valid = await formRef.value.validate()
  if (!valid) return
  await ProfileApi.updatePassword(formData.value.oldPassword, formData.value.newPassword)
  message.success(t('message', 'updateSuccess'))
}

const reset = () => {
  if (!formRef.value) return
  formData.value = {
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  }
  formRef.value.resetFields()
}
</script>

<template>
  <el-form ref="formRef" :labelWidth="120" :model="formData" :rules="formRules" label-position="right">
    <ElFormItem :label="t('profile.password', 'oldPassword')" prop="oldPassword">
      <InputPassword v-model="formData.oldPassword" class="flex-1" :placeholder="t('profile.password', 'oldPwdMsg')" />
    </ElFormItem>
    <ElFormItem :label="t('profile.password', 'newPassword')" prop="newPassword">
      <InputPassword v-model="formData.newPassword" class="flex-1" :placeholder="t('profile.password', 'newPwdMsg')" />
    </ElFormItem>
    <ElFormItem :label="t('profile.password', 'confirmPassword')" prop="confirmPassword">
      <InputPassword v-model="formData.confirmPassword" class="flex-1" :placeholder="t('profile.password', 'cfPwdMsg')" />
    </ElFormItem>
    <ElFormItem class="!mt-12px">
      <div class="flex flex-1 items-center justify-center">
        <CButton :title="t('action', 'save')" type="primary" @click="submit()" />
        <CButton :title="t('action', 'reset')" type="danger" @click="reset()" />
      </div>
    </ElFormItem>
  </el-form>
</template>

<style scoped lang="scss"></style>
